#include "../include/ThreadPool.hpp"
#include "../include/Thread.hpp"
#include "../include/Task.hpp"

#include <unistd.h>

#include <chrono>
#include <thread>
#include <iostream>

using std::cout;
using std::endl;


namespace cdm{

ThreadPool::ThreadPool(size_t thdNum,size_t taskNum)
:_threadQue(),
_threadSize(thdNum),
_taskSize(taskNum),
_taskQue(_taskSize),
_isExit(false){
}

ThreadPool::~ThreadPool(){

}

void ThreadPool::start(){
    //创建线程
    for(size_t i =0; i< _threadSize;++i){
        /* unique_ptr<Thread> threadptr(new MyThread(*this)); */
        /* _threadQue.push_back(std::move(threadptr)); */
        //基于对象的写法
        unique_ptr<Thread> fnct(new Thread(std::bind(&ThreadPool::doTask,this)));
        _threadQue.push_back(std::move(fnct));
    }
    for(auto &ele:_threadQue){
        ele->start();
    }
    printf("ThreadPool start\n");
}

void ThreadPool::stop(){
    while(!_taskQue.isEmpty()){
        sleep(1);
    }
    _isExit = true;
    _taskQue.wakeUp();
    //加空任务，配合doTask的else判断，可以直接退出
    /* for(size_t i = 0; i< _threadSize;i++){ */
    /*     _taskQue.push(nullptr); */
    /* } */

    
    for(const auto &ele: _threadQue){
        ele->join();
    }
}

void ThreadPool::addTask(Task &&cb){
    if(cb){
        _taskQue.push(std::move(cb));
    }
}


void ThreadPool::doTask(){
    while(!_isExit){
        Task cb = _taskQue.pop();
        if(cb){
            cb();
        }
        else{
            /* if(!_isExit){ */
                printf("ptask is nullptr\n");
            /* }else{ */
                /* break; */
            /* } */
            
        }
    }
}


}//end of namespace

